package com.wshare.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.wshare.entity.Account;
import com.wshare.entity.Role;
import com.wshare.service.interfaces.IAccountService;


public class AccountUserDetailsService implements UserDetailsService{

	
	@Autowired
	IAccountService accountService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		System.out.println("load user");
		return this.getUserDetailByUsername(username);
	}
	
	@SuppressWarnings("deprecation")
	public Collection<GrantedAuthority> getAuthorities(List<Role> roles)
	{
		System.out.println("kivay");
		try {
			System.out.println(roles);
		} catch (Exception e) {
			System.out.println("loi roi:"+e);
		}
		
		
		 List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		 for (Role role : roles) {
			authList.add(new GrantedAuthorityImpl(role.getRolName()));
		 }
		 
		 System.out.println("run ok");
		return authList;
	}
	
	public UserDetails getUserDetailByUsername(String username)
	{
		System.out.println("null a:"+accountService);
		UserDetails user=null;
		Account acc= accountService.getByCol("username", username).get(0);
		user= new User(acc.getUsername(),acc.getPassword(),true,true,true,true,getAuthorities((List<Role>) acc.getlRoles()));
		return user;
	}
	
}
